﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using Microsoft.Win32;
using System.Diagnostics;
using System.IO;
using System.Threading;

namespace MyNotepad
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(String[] args)
        {
            if (Properties.Settings.Default.IsFirstRun)
            {
                SetRegKeys();
                Properties.Settings.Default.IsFirstRun = false;
                Properties.Settings.Default.Save();
            }

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            string path = Application.StartupPath;

            List<string> reqPaths = new List<string>();
            reqPaths.Add(Path.Combine(path, "MyNotepadLicense.txt"));
            reqPaths.Add(Path.Combine(path, "WindowsFormsUIDockingLicense.txt"));
            reqPaths.Add(Path.Combine(path, "ScintillaNETLicense.txt"));
            reqPaths.Add(Path.Combine(path, "ScintillaNet.dll"));
            reqPaths.Add(Path.Combine(path, "WeifenLuo.WinFormsUI.Docking.dll"));
            reqPaths.Add(Path.Combine(path, "SciLexer.dll"));

            foreach (string file in reqPaths)
            {
                if (!File.Exists(file))
                {
                    FileInfo f = new FileInfo(file);
                    MessageBox.Show("A required file \"" + f.Name + "\" is missing. Please reinstall My Notepad to resolve the issue.", "My Notepad", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    Environment.Exit(1);
                }
            }
            
            SingleInstanceApplication app = new SingleInstanceApplication();
            app.Run(args);            
        }

        private static void SetRegKeys()
        {
            RegistryKey rkey = Registry.ClassesRoot.CreateSubKey(".note");
            rkey.SetValue("", "MyNotepadFile");
            RegistryKey notepadkey = Registry.ClassesRoot.CreateSubKey("MyNotepadFile");
            RegistryKey defaultIcon = notepadkey.CreateSubKey("DefaultIcon");
            defaultIcon.SetValue("", Path.Combine(Application.StartupPath, "icon.ico"));
            notepadkey = notepadkey.CreateSubKey("shell");
            notepadkey = notepadkey.CreateSubKey("open");
            notepadkey = notepadkey.CreateSubKey("command");
            notepadkey.SetValue("", "\"" + Application.ExecutablePath + "\"" + " \"%1\"");
        }
    }
}
